package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    private VideoService videoService;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;




    // 视频列表查询     key:video_用户id_pageNum_pageSize
    @Cacheable(value = "tanhua",key = "'video_'+#userId+'_'+#pageNum+'_'+#pageSiz")
    public PageBeanVo findVideoVoByPage(Long userId, Integer pageNum, Integer pageSiz) {
        System.out.println("查询数据库。。。。");

        // 1.调用rpc查询推荐视频分页对象
        PageBeanVo pageBeanVo = videoService.findVideoByPage(userId, pageNum, pageSiz);
        // 2.封装videoVo
        // 2-1 声明voList
        List<VideoVo> voList = new ArrayList<>();
        // 2-2 获取videoList
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        // 2-3 遍历
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                // 查询视频发布人的信息
                UserInfo videoUserInfo = userInfoService.findById(video.getUserId());
                // 创建vo
                VideoVo vo = new VideoVo();
                vo.setUserInfo(videoUserInfo); // 发布人信息
                vo.setVideo(video); // 视频详情

                // 是否关注
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER, userId,video.getUserId()))) {
                    vo.setHasFocus(1);
                }

                // 添加到集合
                voList.add(vo);

            }
        }

        // 3.将vo设置到分页对象
        pageBeanVo.setItems(voList);

        // 4.返回分页对象
        return pageBeanVo;
    }

    // 发布视频
    @CacheEvict(value = "tanhua",key = "'video_'+#userId+'_*'")
    public void publishVideo(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        // 1.上传封面
        StorePath picPath = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(), FileUtil.extName(videoThumbnail.getOriginalFilename()), null);
        String picUrl = webServer.getWebServerUrl() + picPath.getFullPath();
        // 2.上传视频
        StorePath videoPath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = webServer.getWebServerUrl() + videoPath.getFullPath();
        // 3.封装video
        Video video = new Video();
        video.setCreated(System.currentTimeMillis()); // 发布时间
        video.setUserId(userId); // 发布人id
        video.setPicUrl(picUrl); // 视频封面
        video.setVideoUrl(videoUrl);// 视频内容
        video.setText("坐等吃瓜~~~~");
        // 4.调用rpc保存
        videoService.saveVideo(video);

    }

    // 视频关注
    public void saveFocusUser(Long focusUserId) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.封装focusUser对象
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis()); // 关注时间
        focusUser.setUserId(userId); // 你的id
        focusUser.setFocusUserId(focusUserId); // 对方id
        // 3.调用rpc保存
        focusUserService.saveFocusUser(focusUser);
        // 4.将关注标记存储到reids中
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId), "1");

    }

    // 视频取消关注
    public void removeFocusUser(Long focusUserId) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc删除
        focusUserService.removeFocusUser(userId, focusUserId);
        // 3.移除redis关注标记
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId));
    }
}
